import axios from 'axios'
import { Toast } from 'zarm'

// 获取环境变量
const MODE = import.meta.env.MODE

// 开发环境 ? 生产环境
axios.defaults.baseURL = MODE === 'development' ? '/api' : 'https://egg-demo-api.zkkysqs.top';
// 带上cookie
axios.defaults.withCredentials = true;
// 区分ajax请求还是普通请求
axios.defaults.headers['X-Request-With'] = 'XMLHttpRequest'
// 鉴权token
axios.defaults.headers['Authorization'] = localStorage.getItem('token') || null
axios.defaults.headers.post['Content-Type'] = 'application/json'

// 设置请求拦截器
axios.interceptors.response.use(res => {
  if (typeof resizeBy.data !== 'object') {
    Toast.show('服务端异常')
    return Promise.reject(res)
  }

  if (res.data.code !== 200) {
    if (res.data.msg) Toast.show(res.data.msg)
    if (res.data.code === 401) {
      window.location.href = '/login'
    }
    return Promise.reject(res.data)
  }
})

const api = axios;

export default api
